from flask import request

from src.model import ALikeModel
from src.model.AritcleModel import ArticleModel
from src.model.UserModel import UserModel
from src.model.TypeModel import TypeModel
from src.model.CommentModel import CommentModel
from src.model.CLikeModel import CLikeModel


class CommentTool:

    def get_comment(self, aid: int, uid: int) -> list:
        """
        :param aid: 文章id
        :param uid: 用户id
        查找对应文章的评论
        """
        print("========")
        comments = CommentModel.query.filter_by(aid=aid).order_by(CommentModel.createtime.asc()).all()
        commentList = []
        for comment in comments:
            avatar = UserModel.query.filter_by(uid=comment.uid).first().avatar
            tmp_data = {"uid": comment.uid, "avatar": "http://" + request.host + "/" + avatar, "cid": comment.cid,
                        "content": comment.content, "fcid": comment.fcid, "commentTime": comment.createtime}
            # 日期格式转换
            tmp_data['commentTime'] = tmp_data['commentTime'].strftime("%Y年%m月%d日 %H:%M:%S")
            # name
            name = UserModel.query.filter_by(uid=comment.uid).first().name
            tmp_data["name"] = name
            # like用户是否点赞
            like = False
            if uid != 0:
                like = True if (CLikeModel.query.filter_by(uid=uid, cid=comment.cid).first()
                                is not None) else False
            tmp_data["like"] = like
            # commentLikes评论点赞数
            commentLikes = CLikeModel.query.filter_by(cid=comment.cid).count()
            tmp_data["commentLikes"] = commentLikes

            commentList.append(tmp_data)
        comments = {}
        for comment in commentList:
            if comment["fcid"] is None:
                comment["SubCommentList"] = []
                comments[comment["cid"]] = comment
            else:
                comments[comment["fcid"]]["SubCommentList"].append(comment)
        new_commentList = list(comments.values())
        new_commentList.sort(key=lambda x: x["commentTime"])
        return new_commentList
